// Copyright 2006 PR1ME. All Rights Reserved.
import java.io.DataOutput;
import java.io.IOException;

public class BitWriter {

  public BitWriter(DataOutput outFile) {
    this.outFile = outFile;
  }

  public void finish() throws IOException {
    if (bitmask != 0x1) {
      advance();
    }
    flush();
  }

  public void flush() throws IOException {
    outFile.write(buf, 0, pos);
    buf[0] = buf[pos];
    pos = 0;
  }

  public void write(boolean b) throws IOException {
    if (b) {
      buf[pos] |= bitmask;
    }

    if (bitmask == 0x80) {
      advance();
    } else {
      bitmask <<= 1;
    }

  }

  private void advance() throws IOException {
    // move to next byte
    bitmask = 0x1;
    ++pos;
    if (pos == buf.length) {
      outFile.write(buf);
      pos = 0;
    }

    // clear upcoming byte
    buf[pos] = 0;
  }

  private int bitmask = 0x1;
  private final byte[] buf = new byte[1024];
  private DataOutput outFile;
  private int pos = 0;
}
